<template>
  <div id="app">
    <Home class="home" :class="{ 'login' : isHome }"></Home>
    <Login :class="{ 'login' : isLogin }"></Login>
  </div>
</template>

<script>
import Home from './components/home.vue'
import Login from './components/login.vue'
import Qs from 'qs'
import { getPublicKey, login } from './require/api.js'
export default {
  components: {
    Home,
    Login
  },
  data () {
    return {
      isHome: false,
      isLogin: true
    }
  },
  methods: {
    async prePublicKey (e) {
      this.$store.commit('gztPublicKey', e.data) // 保存公钥
      window.localStorage.setItem('publicKey', this.$store.state.publicKey) // 保存公钥至H5
      this.$message({
        message: e.isMessage,
        type: 'success'
      })
      if (window.localStorage.getItem('token')) {
        if (window.localStorage.getItem('user') !== '' && window.localStorage.getItem('password') !== '') {
          const logindata = Qs.stringify({
            user: window.localStorage.getItem('user'),
            password: window.localStorage.getItem('password')
          })
          const { data: res } = await login(logindata)
          setTimeout(() => {
            if (res.code !== 0) {
              this.$message.error('登录失效,请重新登录')
              this.isHome = true
              this.isLogin = false
            } else {
              window.localStorage.setItem('token', res.data.token)
              const rsaData = {
                rsaUser: window.localStorage.getItem('user'),
                rsaPassword: window.localStorage.getItem('password'),
                token: res.data.token
              }
              this.$store.commit('gztUserInfo', rsaData)
            }
          }, 3000)
        }
      } else {
        this.isHome = true
        this.isLogin = false
      }
    },
    loginCode () {
      this.isHome = false
      this.isLogin = true
    }
  },
  async mounted () {
    const { data: res } = await getPublicKey() // 获取公钥
    this.prePublicKey(res)
  }
}
</script>
<style lang="scss" scoped>
#app{
  width: 100%;
  height: 718px;
  background: #f6f6f6;
}
.login{
  display: none;
}
</style>
